package com.kd.xjoa.scheduled.search.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.kd.xjoa.scheduled.search.bean.IndexContent;
import com.kd.xjoa.scheduled.search.bean.IndexParam;
import com.kd.xjoa.scheduled.search.bean.IndexResult;
import com.kd.yq.common.utils.CommonUtils;
import com.kd.yq.common.utils.HttpConnectUtil;
import com.kd.yq.common.utils.HttpRequestUtil;
import com.kd.yq.common.utils.ObjectToCollectionUtil;

public class IndexSearchUtil {
	
	private static final Log logger = LogFactory.getLog(IndexSearchUtil.class);

	private static String URL_SEARCH = ResourceBundle.getBundle("searchServer").getString("index.server.url")+"/xjnews/search";
	
	private static String URL_QUERY = ResourceBundle.getBundle("searchServer").getString("index.server.url")+"/xjnews/query";
	
	public static String sendPost(IndexParam param,String url){
		JSONObject json = HttpRequestUtil.sendPost(url, ObjectToCollectionUtil.objToMap(param));
		return json!=null?json.toJSONString():null;
	}
	
	public static String sendGet(IndexParam param,String url){
		if(param == null){
			return null;
		}
		StringBuffer reqUrl = new StringBuffer(url+"?");
		//========
		if(StringUtils.isNotBlank(param.getAuthor())){
			reqUrl.append("&author=").append(encode(param.getAuthor()));
		}
		if(param.getAuthorId() != null){
			reqUrl.append("&authorId=").append(param.getAuthorId());
		}
		if(StringUtils.isNotBlank(param.getContent())){
			reqUrl.append("&content=").append(encode(param.getContent()));
		}
		if(StringUtils.isNotBlank(param.getDomain())){
			reqUrl.append("&domain=").append(param.getDomain());
		}
		if(StringUtils.isNotBlank(param.getIds())){
			reqUrl.append("&ids=").append(param.getIds());
		}
		if(StringUtils.isNotBlank(param.getInforLeve())){
			reqUrl.append("&inforLeve=").append(param.getInforLeve());
		}
		if(StringUtils.isNotBlank(param.getTitle())){
			reqUrl.append("&title=").append(encode(param.getTitle()));
		}
		if(StringUtils.isNotBlank(param.getType())){
			reqUrl.append("&type=").append(param.getType());
		}
		if(StringUtils.isNotBlank(param.getSource())){
			reqUrl.append("&source=").append(param.getSource());
		}
		if(param.getStartTime() != null){
			reqUrl.append("&startTime=").append(param.getStartTime());
		}
		if(param.getEndTime() != null){
			reqUrl.append("&endTime=").append(param.getEndTime());
		}
		if(StringUtils.isNotBlank(param.getSort())){
			reqUrl.append("&sort=").append(param.getSort());
		}
		if(param.getPercentage() != null){
			reqUrl.append("&percentage=").append(param.getPercentage());
		}
		
		reqUrl.append("&pageNum=").append(param.getPageNum());
		reqUrl.append("&pageSize=").append(param.getPageSize());
		//========
		System.out.println(reqUrl.toString());
		return HttpConnectUtil.doGet(reqUrl.toString());
	}
	
	private static String encode(String str){
		String result = null;
		try {
			result = new String(URLEncoder.encode(str, "UTF-8").getBytes(), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return str;
		}
		return result;
	}
	/**
	 * 执行搜索
	 * @param query
	 * @return
	 */
	public static IndexResult query(IndexParam param){
		//String result = sendPost(query);
		
		String result = sendGet(param,URL_QUERY);
		if(StringUtils.isBlank(result)){
			return null;
		}
		//System.out.println(result);
		return JSONObject.parseObject(result, IndexResult.class);
	}
	
	public static IndexResult search(IndexParam param){
		//String result = sendPost(param,URL_SEARCH);
		
		String result = sendGet(param,URL_SEARCH);
		if(StringUtils.isBlank(result)){
			return null;
		}
		//System.out.println(result);
		IndexResult indexResult = null;
		try {
			indexResult=JSONObject.parseObject(result, IndexResult.class);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return indexResult;
	}
	
	/**
	 * 根据id查找
	 * @param id
	 * @return
	 */
	public static IndexContent queryById(String id){
		IndexParam param = new IndexParam();
		param.setIds(id);
		
		IndexResult result = query(param);
		if(result == null){
			logger.error("index search error, result null ");
			return null;
		} 
		if(result.getCode() != 200){
			logger.error("index search error, " + result.toString());
			return null;
		}
		if(result.getData() == null || CommonUtils.isBlank(result.getData().getContent())){
			logger.error("索引id:"+id+",index search content null, " + result.toString());
			return null;
		}
		return result.getData().getContent().get(0);
	}
	
	
	public static int queryCounts(IndexParam param){
		IndexResult result = search(param);
		if(result == null){
			logger.error("index search error, result null ");
			return 0;
		} 
		if(result.getCode() != 200){
			logger.error("index search error, " + result.toString());
			return 0;
		}
		if(result.getData() == null){
			return 0;
		}
		return result.getData().getTotalElements();
	}
	
	/**
	 * 取词条在内容中最开始出现位置的完整一句话的开始下标
	 * @param content
	 * @param word
	 * @return
	 */
	private static int getLastCharIndex(String content,String words){
		int result = 0;
		if(StringUtils.isBlank(content) || StringUtils.isBlank(words)){
			return result;
		}
		String[] wordArrs = words.split(",");
		List<Integer> lastFHIndexList = new ArrayList<Integer>();
		for (int i = 0; i < wordArrs.length; i++) {
			int charIndex = content.indexOf(wordArrs[i]);
			if(charIndex > 0){
				Integer[] indexs = {content.lastIndexOf(",", charIndex),content.lastIndexOf("，", charIndex),
						content.lastIndexOf(".", charIndex),content.lastIndexOf("。，", charIndex),
						content.lastIndexOf("！", charIndex),content.lastIndexOf("！", charIndex),
						content.lastIndexOf(";", charIndex),content.lastIndexOf("；", charIndex),
						content.lastIndexOf("?", charIndex),content.lastIndexOf("？", charIndex),
						content.lastIndexOf(" ", charIndex),content.lastIndexOf("	", charIndex)};
				int lastFHIndex = getMaxByArrs(indexs);
				if(lastFHIndex > 0){
					lastFHIndexList.add(lastFHIndex);
				}
				
			}
		}
		return getMinByArrs(lastFHIndexList.toArray(new Integer[lastFHIndexList.size()]));
	}
	
	/**
	 * 排序取最大值
	 * @param arrs
	 * @return
	 */
	private static int getMaxByArrs(Integer[] arrs){
		if(arrs == null || arrs.length == 0){
			return 0;
		}
		order(arrs);
		return arrs[0];
	}
	/**
	 * 排序取最小值
	 * @param arrs
	 * @return
	 */
	private static int getMinByArrs(Integer[] arrs){
		if(arrs == null || arrs.length == 0){
			return 0;
		}
		order(arrs);
		return arrs[arrs.length-1];
	}
	
	/**
	 * 冒泡排序
	 * @param arrs
	 */
	private static void order(Integer[] arrs){
		for (int i = 0; i < arrs.length-1; i++) {
			for (int j = 0; j < arrs.length-1-i; j++) {
				if(arrs[j] < arrs[j+1]){
					int temp = arrs[j];
					arrs[j] = arrs[j+1];
					arrs[j+1] = temp;
				}
			}
		}
	}
	
	/*public static void main(String[] args) throws MalformedURLException {
		String content = "致敬！我正在看#新疆暴恐案# 央视曝光新疆公安干警与暴恐分子激战牺牲画面 @腾讯视频 http://t.cn/R68PiTY";
		String word = "新疆曝光,xxx";
		int a = getLastCharIndex(content, word);
		System.out.println(content.substring(a+1));
		
		IndexParam param1 = new IndexParam();
		param1.setIds("0E524C5A7946FF602B18BC262EB2C62E");
		IndexResult result1 = IndexSearchUtil.query(param1);
		
		
		IndexParam param2 = new IndexParam();
		param2.setAuthor("zzg96262");
		IndexResult result2 = IndexSearchUtil.search(param2);
		//URL url = new URL("http://www.xjtlmh.com/11");
		//System.out.println(url.getHost());
	}*/
	
	
	
}
